package com.xmcowell.sportpacemaster.views;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import com.xmcowell.sportpacemaster.R;
import com.xmcowell.sportpacemaster.config.Contents;
import com.xmcowell.sportpacemaster.layout.SerialPortService;
import com.xmcowell.sportpacemaster.layout.entity.UserPlanSet;
import com.xmcowell.sportpacemaster.layout.i_run.program.util.ProgramValue;
import com.xmcowell.sportpacemaster.layout.i_run.program.util.SpeedAndSlopeUtil;
import com.xmcowell.sportpacemaster.layout.i_run.program.util.SpeedAndSlopeUtil1;
import com.xmcowell.sportpacemaster.utils.DensityUtil;
import com.xmcowell.sportpacemaster.utils.PreferencesUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * workouts里面的program模式的图表
 * Created by Administrator on 2017/8/25 0025.
 */

public class ProgramView extends View {
    public static final String TAG = "ProgramView";

    public Context context;
    public Resources res;
    public DisplayMetrics dm;

    public Paint speedYPaint;//速度的Y轴
    public Paint XPaint;//X轴
    public Paint slopeYPaint;//坡度的Y轴
    public Paint speedPaint;//速度折线
    public Paint slopePaint;//坡度柱状
    public Bitmap arrow;//指示器图片

    public int canvasHeight = 0;//控件的高度
    public int canvasWidth = 0;//控件的宽度
    public float slineWidth = 0;//曲线的宽度范围
    public float slineStart = 0;//曲线的起点位置
    public static float sline_left_width = 0;//曲线距离左侧的边距
    public static final float LEFT_WIDTH = 25;//左侧的边距
    public float rightWidth = 0;//右侧的边距
    public float space_lenght = 0;//坐标刻度间的间隔
    public static final float coordinate_lenght = 10;//坐标刻度的长度
    public static final float y_lenght = 10;//Y底部坐标刻度距离底部的长度（即x轴距离底部的长度）

    public int leftSize;//左侧Y轴的坐标个数
    public int rightSize;//右侧Y轴的坐标个数
    public int maxValue;
    public ArrayList<Integer> speedData;//速度的值
    public ArrayList<Integer> slopeData;//坡度的值
    public int timeData;//时间的值(1分钟为一个柱状)
    public static int X_SIZE = 15;//默认将X轴分成11份
    public float slopeWidth = 0;//柱状的宽度
    public float spaceWidth = 0;//柱状间隔的宽度
    private ArrayList<Point> mPointSpeeds;//折线上总点数
    private ArrayList<Point> mPointSlopes;//柱状上总点数

    private boolean isMeasure = true;

    public ProgramView(Context context) {
        this(context, null);
    }

    public ProgramView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);

    }

    public ProgramView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        initView(context);
        initPaint();
    }

    private void initView(Context context) {
        this.res = context.getResources();
        dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);

        leftSize = getSpeedMax(context) + 1;
        rightSize = 15 + 1;
        maxValue = leftSize > rightSize ? leftSize : rightSize;
        speedData = new ArrayList<>();
        slopeData = new ArrayList<>();

        Log.e(TAG, "执行initView（）");
    }

    private void initPaint() {
        //速度Y轴的画笔
        speedYPaint = new Paint(Paint.ANTI_ALIAS_FLAG);//Paint.ANTI_ALIAS_FLAG  －－用于绘制时抗锯齿
        speedYPaint.setColor(res.getColor(R.color.color_line));
        speedYPaint.setStrokeWidth(dip2px(1f));
        //速度的折线画笔
        speedPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        speedPaint.setColor(res.getColor(R.color.color_line));
        speedPaint.setStrokeWidth(dip2px(10f));
        speedPaint.setStyle(Paint.Style.STROKE);
        //x轴画笔
        XPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        XPaint.setColor(res.getColor(R.color.white));
        XPaint.setStrokeWidth(dip2px(1f));
        //坡度Y轴的画笔
        slopeYPaint = new Paint(Paint.ANTI_ALIAS_FLAG);//Paint.ANTI_ALIAS_FLAG  －－用于绘制时抗锯齿
        slopeYPaint.setColor(res.getColor(R.color.white));
        slopeYPaint.setStrokeWidth(dip2px(1f));
        //坡度柱状的画笔
        slopePaint = new Paint(Paint.ANTI_ALIAS_FLAG);//Paint.ANTI_ALIAS_FLAG  －－用于绘制时抗锯齿
        slopePaint.setColor(res.getColor(R.color.program_slope));
        slopePaint.setStrokeWidth(dip2px(1f));
        slopePaint.setStyle(Paint.Style.FILL);
        //箭头指示器
        arrow = BitmapFactory.decodeResource(context.getResources(),
                R.mipmap.icon_arrow2);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        Log.e(TAG, "onSizeChanged（）");
        if (isMeasure) {
            this.canvasHeight = getHeight();
            this.canvasWidth = getWidth();
            isMeasure = false;
            if (maxValue > 1) {
                space_lenght = Float.valueOf(canvasHeight - y_lenght) / (maxValue);
            }
            sline_left_width = LEFT_WIDTH + coordinate_lenght + (coordinate_lenght / 3);//曲线距离左侧的宽度
            slineWidth = canvasWidth - 2 * sline_left_width;//总宽度-2*（Y坐标轴距离左侧宽度+Y轴刻度的长度+（Y轴刻度的长度/4））
            slopeWidth = slineWidth * 3 / (5 * X_SIZE + 2);//slineWidth = （空格宽度+柱状宽度）*个数（即X_SIZE）+空格宽度，空格宽度=2/3*柱状宽度
            spaceWidth = slopeWidth * 2 / 3;//空格宽度
        }
    }

    float x = 0;//手指所触碰的x值
    float length = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                x = event.getX();
                Log.e(TAG, "手指点击控件,x = " + x);
                break;
            case MotionEvent.ACTION_MOVE:
                if (timeData >= X_SIZE) {
//                    flag == 1||
                    if (!(SerialPortService.getInstatnce().isStaring() || SerialPortService.getInstatnce().isRun() || SerialPortService.getInstatnce().getStopping())) {
                        Log.e(TAG, "手指滑动控件,flag = " + flag);
                        float x_move = event.getX();
                        slineStart = x_move - x + length;
                        if (slineStart > 0) {
                            slineStart = 0;
                        }
                        if (slineStart < (0 - ((timeData - X_SIZE) * (spaceWidth + slopeWidth)))) {
                            slineStart = 0 - ((timeData - X_SIZE) * (spaceWidth + slopeWidth));
                        }
                        invalidate();
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                Log.e(TAG, "手指离开空间");
                length = slineStart;
                break;
        }
        if ((SerialPortService.getInstatnce().isStaring() || SerialPortService.getInstatnce().isRun() || SerialPortService.getInstatnce().getStopping()))
            return super.onTouchEvent(event);
        return true;

    }

    @Override
    protected void onDraw(Canvas canvas) {
        Log.e(TAG, "onDraw（）");
        super.onDraw(canvas);

        Log.e(TAG, "2/isDrawXY = " + isDrawXY);
        if (isDrawXY) {
            //是否要绘制xy轴，默认绘制
            drawXLine(canvas);
            drawYLine(canvas);
        }
        mPointSpeeds = getPointSpeeds();
        mPointSlopes = getPointSlopes();
        //限制一下绘制的范围，否者折线会与坐标轴重叠
        canvas.clipRect(sline_left_width, 0, canvasWidth - sline_left_width - 1, canvasHeight - y_lenght);
        if (mPointSpeeds.size() > 0 && mPointSlopes.size() > 0) {
            //设置折线图与柱状图是否要移动
            int min = currentSecond / 60;
            int second = currentSecond % 60;
            float x = mPointSpeeds.get(min).getX() + second / 60f * slopeWidth;
//            if (x > slineWidth / 2 + sline_left_width
//                    && mPointSpeeds.get(mPointSpeeds.size() - 1).getX() > (canvasWidth - sline_left_width - spaceWidth - slopeWidth)) {
//                slineStart = (slineWidth / 2 + sline_left_width - x) + slineStart;
//            }
            if (x > (5 * spaceWidth + 4 * slopeWidth) + sline_left_width
                    && mPointSpeeds.get(mPointSpeeds.size() - 1).getX() > (canvasWidth - sline_left_width - spaceWidth - slopeWidth)) {
                slineStart = ((5 * spaceWidth + 4 * slopeWidth) + sline_left_width - x) + slineStart;
            }
            drawRect(canvas);
            drawLine(canvas);
            drawBitmap(canvas);
        }
    }

    /**
     * 获取速度总点数
     *
     * @return
     */
    private ArrayList<Point> getPointSpeeds() {
        ArrayList<Float> xList = new ArrayList<>();//x的坐标点
        for (int i = 0; i < speedData.size(); i++) {
            xList.add(sline_left_width + spaceWidth + i * (spaceWidth + slopeWidth) + slineStart);//空格宽度+i*（空格宽度+柱状宽度）+起始点位置
        }
        ArrayList<Point> points = new ArrayList<Point>();
        float centerH = canvasHeight - y_lenght;//- bottom_y;
        for (int i = 0; i < speedData.size(); i++) {
            int ph = (int) (centerH - (centerH * speedData.get(i) / 10f / maxValue));
            Point point = new Point();
            point.setX(xList.get(i));
            point.setY(ph);
            points.add(point);
        }
        return points;
    }

    /**
     * 获取坡度总点数
     *
     * @return
     */
    private ArrayList<Point> getPointSlopes() {
        ArrayList<Float> xList = new ArrayList<>();//x的坐标点
        for (int i = 0; i < slopeData.size(); i++) {
            xList.add(sline_left_width + spaceWidth + i * (spaceWidth + slopeWidth) + slineStart);//空格宽度+i*（空格宽度+柱状宽度）+起始点位置
        }
        ArrayList<Point> points = new ArrayList<Point>();
        float centerH = canvasHeight - y_lenght;//- bottom_y;
        for (int i = 0; i < slopeData.size(); i++) {
            int ph = (int) (centerH - (centerH * slopeData.get(i) / 1f / maxValue));
            if (ph == ((int) (centerH))) {
                ph = (int) (centerH - 3);
            }
            Point point = new Point();
            point.setX(xList.get(i));
            point.setY(ph);
            points.add(point);
        }
        return points;
    }

    /**
     * 画折线
     *
     * @param canvas
     */
    private void drawLine(Canvas canvas) {
        Path path = new Path();
        path.moveTo(mPointSpeeds.get(0).getX(), mPointSpeeds.get(0).getY());
        path.lineTo(mPointSpeeds.get(0).getX() + slopeWidth, mPointSpeeds.get(0).getY());
        for (int i = 1; i < mPointSpeeds.size(); i++) {
            path.lineTo(mPointSpeeds.get(i).getX(), mPointSpeeds.get(i).getY());
            path.lineTo(mPointSpeeds.get(i).getX() + slopeWidth, mPointSpeeds.get(i).getY());
        }
        canvas.drawPath(path, speedPaint);
        path.reset();
        path.close();
    }

    /**
     * 画指示器
     *
     * @param canvas
     */

    float x1 = 0;
    float y1 = 0;

    private void drawBitmap(Canvas canvas) {
        int min = currentSecond / 60;
        int second = currentSecond % 60;
        //画箭头指示器
        float x = mPointSpeeds.get(min).getX() + second / 60f * slopeWidth;
        float y = mPointSpeeds.get(min).getY();
        double argle = 0f;//箭头角度
        argle = 0;
        Matrix matrix = new Matrix();
        float ar = (float) (argle / Math.PI * 180);
        matrix.postRotate(ar, arrow.getWidth() / 2, arrow.getHeight() / 2);
        if (x < slineWidth / 2 + sline_left_width
                || mPointSpeeds.get(mPointSpeeds.size() - 1).getX() <= (canvasWidth - sline_left_width - spaceWidth - slopeWidth)) {
            x1 = x - arrow.getWidth() / 2 + 5;
        }
        y1 = y - arrow.getHeight() / 2;
        matrix.postTranslate(x1, y1);
        canvas.drawBitmap(arrow, matrix, speedPaint);
    }

    /**
     * 画矩形柱状
     *
     * @param canvas
     */
    private void drawRect(Canvas canvas) {
        for (int i = 0; i < mPointSlopes.size(); i++) {
            Point start = mPointSlopes.get(i);
            canvas.drawRect(start.getX(), start.getY(), start.getX() + slopeWidth, canvasHeight - 10, slopePaint);
        }
    }

    /**
     * 画X轴和Y轴的坐标值
     *
     * @param canvas
     */
    public void drawXLine(Canvas canvas) {
        //画X轴
        canvas.drawLine(LEFT_WIDTH, canvasHeight - 10, canvasWidth - LEFT_WIDTH, canvasHeight - 10, XPaint);
        //循环画出横向的线条和Y轴的坐标值
        Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
        p.setTextSize(dip2px(18));
        p.setStrokeWidth(dip2px(1f));
        for (int i = 0; i < maxValue; i++) {
            p.setColor(res.getColor(R.color.color_line));
            p.setTextAlign(Paint.Align.RIGHT);
            //速度Y轴的坐标值
            if (i < leftSize)
                canvas.drawText(String.valueOf(i), 20, (canvasHeight - 5) - i * space_lenght, p);
            //画速度坐标的横向线条
            if (i > 0) {
                canvas.drawLine(LEFT_WIDTH, (canvasHeight - y_lenght) - i * space_lenght,
                        LEFT_WIDTH + coordinate_lenght, (canvasHeight - y_lenght) - i * space_lenght, speedYPaint);
            }
            p.setColor(res.getColor(R.color.program_slope1));
            //画横向线条
            if (i > 0) {
                canvas.drawLine(sline_left_width, (canvasHeight - 10) - i * space_lenght,
                        canvasWidth - sline_left_width, (canvasHeight - 10) - i * space_lenght, p);
            }
            p.setColor(res.getColor(R.color.white));
            p.setTextAlign(Paint.Align.RIGHT);
            //坡度Y轴的坐标值
            if (i % 3 == 0 && i < rightSize) {
                canvas.drawText(String.valueOf(i), canvasWidth - 5, (canvasHeight - 5) - i * space_lenght, p);
            }
            //画坡度坐标的横向线条
            if (i > 0) {
                canvas.drawLine(canvasWidth - LEFT_WIDTH,
                        (canvasHeight - y_lenght) - i * space_lenght,
                        canvasWidth - LEFT_WIDTH - coordinate_lenght,
                        (canvasHeight - y_lenght) - i * space_lenght,
                        slopeYPaint);
            }
        }
    }

    /**
     * 画Y轴
     *
     * @param canvas
     */
    public void drawYLine(Canvas canvas) {
        canvas.drawLine(LEFT_WIDTH, 0, LEFT_WIDTH, canvasHeight - 10, speedYPaint);
        canvas.drawLine(canvasWidth - LEFT_WIDTH, 0, canvasWidth - LEFT_WIDTH, canvasHeight - 10 - 1, slopeYPaint);
    }

    /**
     * 设置跑步数据
     */
    public void setData(ProgramValue value) {
        setTime(value.getTime());
        speedData = value.getSpeed();
        slopeData = value.getSlope();
        Log.e(TAG, "speedData.size = " + speedData.size() + ",slopeData.size = " + slopeData.size());

        invalidate();
    }

    public void setTime(int time) {
        timeData = time;
    }

    public int currentSecond;//当前进度（第几秒）

    public void setPro(int pro) {
        this.currentSecond = pro;
        invalidate();
    }

    public int flag = 1;//1为允许，0为禁止

    /**
     * 是否允许手指滑动
     *
     * @param flag
     */
    public void setState(int flag) {
        this.flag = flag;
    }

    private boolean isDrawXY = true;

    /**
     * 是否要绘制xy轴
     */
    public void setXYLine(boolean isDrawXY) {
        this.isDrawXY = isDrawXY;
        Log.e(TAG, "1/isDrawXY = " + this.isDrawXY);
        invalidate();
    }

    /**
     * 重置
     */
    public void reset() {
        length = 0;
        slineStart = 0;
        x1 = 0;
        y1 = 0;
    }

    private int getSpeedMax(Context context) {
        boolean unit = PreferencesUtils.getBooleanFromSPMap(context, Contents.UNITS);
        int speedMax = unit ? 20 : 12;
        return speedMax;
    }

    private int dip2px(float dpValue) {
        return (int) (dpValue * dm.density + 0.5f);
    }

    /**
     * 坐标点实体类
     */
    public class Point {
        private float x;
        private float y;

        public float getX() {
            return x;
        }

        public void setX(float x) {
            this.x = x;
        }

        public float getY() {
            return y;
        }

        public void setY(float y) {
            this.y = y;
        }
    }
}
